import { Injectable } from '@nestjs/common';
import { JwtService as NestJwtService } from '@nestjs/jwt';
import { ConfigService } from '@nestjs/config';
import { JwtPayload, currentUserToJwtPayload } from './types/jwt.type';
import { JwtTimeUtil } from './utils/jwt-time.util';

/**
 * JWT 认证服务
 *
 * 职责：
 * - JWT Token 的生成和验证
 * - 登录响应格式化
 *
 * 注意：密码加密请使用 CryptoUtil（来自 auth/common）
 */
@Injectable()
export class JwtService {
  constructor(
    private readonly nestJwtService: NestJwtService,
    private readonly configService: ConfigService
  ) {}

  /**
   * 生成 JWT Token
   */
  async generateToken(payload: JwtPayload): Promise<string> {
    return this.nestJwtService.sign(payload);
  }

  /**
   * 验证 Token
   */
  async verifyToken(token: string): Promise<JwtPayload> {
    return this.nestJwtService.verify(token);
  }

  /**
   * 生成登录响应
   */
  async login(user: { id: string; username: string; roles?: string[]; permissions?: string[] }) {
    const payload = currentUserToJwtPayload({
      userId: user.id,
      username: user.username,
      roles: user.roles || [],
      permissions: user.permissions || [],
    });

    const accessToken = await this.generateToken(payload);

    // 从配置获取过期时间
    const expiresIn = this.getExpiresInSeconds();

    return {
      accessToken,
      tokenType: 'Bearer',
      expiresIn, // 单位：秒
      user: {
        id: user.id,
        username: user.username,
        roles: user.roles,
        permissions: user.permissions,
      },
    };
  }

  /**
   * 获取 JWT 过期时间（秒）
   *
   * @returns JWT 过期时间（秒）
   */
  getExpiresInSeconds(): number {
    const expiresInConfig = this.configService.get('JWT_EXPIRES_IN') || '7d';
    return JwtTimeUtil.toSeconds(expiresInConfig);
  }
}

